package com.spc.redis.serializer;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.spc.redis.serializer.SerializerUtil.isPrimitiveOrString;

/**
 * @author alex
 * @version v1.0 2021/3/18
 */
public abstract class AbstractSerializer implements Serializer {

    private static final Logger logger = LoggerFactory.getLogger(AbstractSerializer.class);


    /**
     * to primitive value
     * @param value
     * @param clazz
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    protected <T> T toPrimitiveValue(String value, Class<T> clazz) {
        if (!isPrimitiveOrString(clazz)) {
            logger.error("class [{}] not primitive or string", clazz.getCanonicalName());
            return (T) value;
        }
        if (clazz.isAssignableFrom(int.class) ||
                clazz.isAssignableFrom(Integer.class)) {
            return (T) Integer.valueOf(value);
        } else if (clazz.isAssignableFrom(long.class) ||
                clazz.isAssignableFrom(Long.class)) {
            return (T) Long.valueOf(value);
        } else if (clazz.isAssignableFrom(float.class) || clazz.isAssignableFrom(Float.class)) {
            return (T) Float.valueOf(value);
        } else if (clazz.isAssignableFrom(double.class) || clazz.isAssignableFrom(Double.class)) {
            return (T) Double.valueOf(value);
        } else if (clazz.isAssignableFrom(boolean.class) || clazz.isAssignableFrom(Boolean.class)) {
            return (T) Boolean.valueOf(value);
        }
        return (T) value;
    }
}
